package com.cloudxingkong.dianyinke.Student.Fragment;

import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Fragment.BaseFragment;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.DDPopupWindow;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.Adapter.TeacherDongTaiAdapter;
import com.cloudxingkong.dianyinke.Student.bean.StudentDt;
import com.cloudxingkong.dianyinke.Uri.studentUri.StudentUri;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 老师动态Fragment
 */
public class TeacherPtitudeFragment extends BaseFragment implements TeacherDongTaiAdapter.getOnTouchDTPosition, DDPopupWindow.setOnClickPopupWindowListener {
//    private int position = 0;
    private View view;
    private List<StudentDt.ListBean> lists;
    private TeacherDongTaiAdapter taiAdapter;
    private PullToRefreshListView pullToRefreshListView ;
    private SharedPreferences sharedPreferences;
//    private int images[]={R.mipmap.test_wave1,R.mipmap.test_wave2,R.mipmap.test_wave3,R.mipmap.test_wave4};
    private String tID;
    private String sessionID;
    private int mPosition;
    private LinearLayout tpCommentLayout;
    private EditText tpCommentEt;
    private Button tpCommentBtn;

    private ProgressDialog progressDialog;
    private DDPopupWindow ddPopupWindowTwo;
    public static TeacherPtitudeFragment getInstance(String teacherID,String sessionID){
        TeacherPtitudeFragment fragment=new TeacherPtitudeFragment();
        Bundle bundle=new Bundle();
        bundle.putString("tID", teacherID);
        bundle.putString("sessionID", sessionID);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_teacher_ptitude,null);
        lists=new ArrayList<>();
        pullToRefreshListView= (PullToRefreshListView) view.findViewById(R.id.lv_teacher_ptitude);
        taiAdapter = new TeacherDongTaiAdapter(lists,getContext(),this);
        pullToRefreshListView.setAdapter(taiAdapter);
        tpCommentBtn= (Button) view.findViewById(R.id.tp_btn_sendcomment);
        tpCommentEt = (EditText) view.findViewById(R.id.tp_et_comment);
        tpCommentLayout = (LinearLayout) view.findViewById(R.id.tp_comment_layout);
        progressDialog=new ProgressDialog(getActivity());
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.setTitle(null);

        Bundle bundle = getArguments();
        if (bundle != null) {
            tID = bundle.get("tID").toString();
            sessionID = bundle.get("sessionID").toString();
        }

        loadData();
        ddPopupWindowTwo = new DDPopupWindow(getActivity(), this);

        return view;
    }

    private void loadData() {
        final String upLoadUrl = ThisUri.SERVER_YUMING+ StudentUri.DYNAMICLIST;   //动态列表
        RequestParams params = new RequestParams(upLoadUrl);
        params.addHeader("cookie", sessionID);
        params.addBodyParameter("teacherId", tID + "");

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("test", "学生端 获取老师动态列表 " + result);
                if (result != null && !result.equals("")) {
                    Message msg = handler.obtainMessage();
                    msg.what = 1;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } else {
                    handler.sendEmptyMessage(2);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("test", "获取老师动态失败  " + ex.getMessage());
                handler.sendEmptyMessage(3);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    String state = (String) msg.obj;
                    if (state!=null&&!state.equals("")){
                        try{
                            Gson gson=new Gson();
                            StudentDt dt = gson.fromJson(state, StudentDt.class);
                            List<StudentDt.ListBean> list = dt.getList();
                            if (list != null && list.size() > 0) {
                                lists.addAll(list);
                                taiAdapter.notifyDataSetChanged();
                            }

                        }catch (Exception e){
                            Log.e("test","老师动态截取异常 "+e.getMessage());
                            Toast.makeText(getActivity(), "还没有动态哦~快去发布一条吧！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case 2:
                    Toast.makeText(getActivity(), "获取动态失败", Toast.LENGTH_SHORT).show();
                case 3:
                    Toast.makeText(getActivity(), "获取动态失败", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    boolean isComm=false;
                    String comResult = (String) msg.obj;
                    Log.e("test","评论结果 "+comResult);
                    Object success = LoginJsonUtils.getJsonFromLogin(comResult).get("success");
                    isComm= (boolean) success;
                    if (isComm) {
                        Toast.makeText(getActivity(), "评论成功!", Toast.LENGTH_SHORT).show();
                        tpCommentEt.setText("");
                        progressDialog.dismiss();
                        tpCommentLayout.setVisibility(View.GONE);
                        lists.clear();
                        loadData();
                    }else{
                        Toast.makeText(getActivity(), "评论失败,请重试!", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                    break;
                case 5:
                    progressDialog.dismiss();
                    lists.clear();
                    loadData();
                    break;
                case 6:
                    Toast.makeText(getActivity(), "操作失败", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                    break;
            }
        }
    };
    //接收position回调
    @Override
    public void getPosition(int position) {

    }

    @Override
    public void getMore(final ImageView iv, final int position) {
        iv.setClickable(true);
        iv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mPosition=position;
                ddPopupWindowTwo.showPopupWindow(iv);
            }
        });
    }

    @Override
    public void onClickZan(View v) {
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ddPopupWindowTwo.dismiss();
                postZan();
            }
        });

    }

    private void postZan() {
        progressDialog.setMessage("正在操作...");
        progressDialog.show();
        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.COMMENT_OR_MSG);
        params.addHeader("cookie",sessionID);
        int id = lists.get(mPosition).getId();
        params.addBodyParameter("dynamicid", id+"");
        params.addBodyParameter("type", "like");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                boolean isPostZan = false;
                Log.e("test", "老师点赞结果 " + result);
                if (result != null && !result.equals("")) {
                    Object success = LoginJsonUtils.getJsonFromLogin(result).get("success");
                    isPostZan = (boolean) success;
                    if (isPostZan) {
                        handler.sendEmptyMessage(5);
                    } else {
                        handler.sendEmptyMessage(6);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onClickComment(View v) {
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ddPopupWindowTwo.dismiss();
                tpCommentLayout.setVisibility(View.VISIBLE);
                postComment();
            }
        });
    }

    private void postComment() {
        tpCommentBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(tpCommentEt.getText())){
                    progressDialog.setMessage("正在发表...");
                    progressDialog.show();
                    String comment = tpCommentEt.getText().toString();
                    RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.COMMENT_OR_MSG);
                    params.addHeader("cookie", sessionID);
                    int id = lists.get(mPosition).getId();
                    Log.e("test","dynamicID : "+id);
                    params.addBodyParameter("dynamicid", id +"");
                    params.addBodyParameter("type", "msg");
                    params.addBodyParameter("msg", comment);
                    x.http().post(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String result) {

                            Message msg = handler.obtainMessage();
                            msg.what = 4;
                            msg.obj = result;
                            handler.sendMessage(msg);
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            progressDialog.dismiss();
                        }

                        @Override
                        public void onCancelled(CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
                }else{
                    Toast.makeText(getActivity(), "尚未输入评论", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
